#pragma once

#include <iostream>
#include <pthread.h>

namespace My_Mutex
{
    class Mutex
    {
    public:
        Mutex(const Mutex &) = delete;
        const Mutex &operator=(const Mutex &) = delete;
        Mutex()
        {
            int n = pthread_mutex_init(&_lock, nullptr);
            if (n != 0)
            {
                std::cerr << "err: pthread_mutex_init" << std::endl;
                exit(1);
            }
        }
        int Lock()
        {
            return pthread_mutex_lock(&_lock);
        }
        int Unlock()
        {
            return pthread_mutex_unlock(&_lock);
        }
        ~Mutex()
        {
            int n = pthread_mutex_destroy(&_lock);
            if (n != 0)
            {
                std::cerr << "err: pthread_mutex_destroy" << std::endl;
                exit(2);
            }
        }

    private:
        pthread_mutex_t _lock;
    };

    class LockGuard
    {
    public:
        LockGuard()
        {
            _lock.Lock();
        }
        ~LockGuard()
        {
            _lock.Unlock();
        }

    private:
        Mutex _lock;
    };
}